package com.appspot.simplebookmarks.service;

import java.util.List;
import java.util.Map;

import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.appspot.simplebookmarks.meta.CollectionMeta;
import com.appspot.simplebookmarks.model.Collection;
import com.google.appengine.api.datastore.Transaction;

public class CollectionService {

    public Collection add(Map<String, Object> input) {
        Collection collection = new Collection();
        BeanUtil.copy(input, collection);
        Integer i = this.getLastOrderNumber(input.get("author").toString());
        collection.setDisplayOrder(i + 1);
        Transaction tx = Datastore.beginTransaction();
        Datastore.put(collection);
        tx.commit();
        return collection;
    }

    public Collection add(Collection collection) {
        Integer i = this.getLastOrderNumber(collection.getAuthor());
        collection.setDisplayOrder(i + 1);
        Transaction tx = Datastore.beginTransaction();
        Datastore.put(collection);
        tx.commit();
        return collection;
    }

    private Integer getLastOrderNumber(String author) {
        List<Collection> c = this.getList(author);
        return c.get(c.size() - 1).getDisplayOrder();
    }

    public List<Collection> getList(String author) {
        CollectionMeta e = CollectionMeta.get();
        List<Collection> list = Datastore.query(e)
                .filter(e.author.equal(author))
                .sort(e.displayOrder.asc)
                .asList();
        if (list.size() == 0) {
            Collection collection = new Collection();
            collection.setName("HOME");
            collection.setAuthor(author);
            collection.setDisplayOrder(1);
            Transaction tx = Datastore.beginTransaction();
            Datastore.put(collection);
            tx.commit();
            list.add(collection);
        }
        return list;
    }
}
